package com.ideaaedi.component.decompile.fernflower;

import org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler;
import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * .class文件字节码提供器
 *
 * @author JustryDeng
 * @since 2021/9/29 14:22:55
 */
public class MemoryBytecodeProvider implements IBytecodeProvider {
    
    public static final String SPECIAL_KEY_PREFIX = "MemoryBytecodeProvider__";
    
    private final ConsoleDecompiler target;
    
    private final Map<String, byte[]> classMatcher;
    
    public MemoryBytecodeProvider(Map<String, Object> options, Map<String, byte[]> classMatcher) {
        this.target = new ConsoleDecompiler(new File("non-exist"), options);
        this.classMatcher = classMatcher;
    }
    
    @Override
    public byte[] getBytecode(String externalPath, String internalPath) throws IOException {
        int idx = externalPath.indexOf(SPECIAL_KEY_PREFIX);
        if (idx >= 0) {
            byte[] classBytes = classMatcher.get(externalPath.substring(idx));
            if (classBytes != null) {
                return classBytes;
            }
        }
        return target.getBytecode(externalPath, internalPath);
    }
}
